"""
python 2d_bird.py
"""

import numpy as np

# 定义 PSO 参数
num_particles = 20  # 粒子数
num_iterations = 500000  # 最大迭代次数
w = 0.5  # 惯性权重
c1 = 2.0  # 个体学习因子
c2 = 2.0  # 社会学习因子
dim = 2  # 问题的维度 (x, y)

# 初始化粒子位置和速度
particles_position = np.random.uniform(-10, 10, (num_particles, dim))
particles_velocity = np.random.uniform(-1, 1, (num_particles, dim))

# 初始化个体和全局最优位置
p_best_position = np.copy(particles_position)
p_best_value = np.array([np.inf] * num_particles)
g_best_position = np.zeros(dim)
g_best_value = np.inf

# 目标函数
def objective_function(x, y):
    return x**2 + y**2

# 主循环
for t in range(num_iterations):
    for i in range(num_particles):
        x, y = particles_position[i]
        fitness = objective_function(x, y)
        
        # 更新个体最优
        if fitness < p_best_value[i]:
            p_best_value[i] = fitness
            p_best_position[i] = particles_position[i]
        
        # 更新全局最优
        if fitness < g_best_value:
            g_best_value = fitness
            g_best_position = particles_position[i]
    
    # 更新速度和位置
    for i in range(num_particles):
        r1, r2 = np.random.rand(2)
        particles_velocity[i] = (w * particles_velocity[i] + 
                                 c1 * r1 * (p_best_position[i] - particles_position[i]) + 
                                 c2 * r2 * (g_best_position - particles_position[i]))
        particles_position[i] += particles_velocity[i]

print("最优解位置:", g_best_position)
print("最优解值:", g_best_value)
